<template>
  <view class="calendar-container">
    <!-- 顶部导航 -->
    <view class="nav-header">
      <view class="back-btn" @tap="handleBack">
        <text class="icon">←</text>
      </view>
      <text class="title">日历</text>
      <view class="placeholder"></view>
    </view>

    <!-- 日历主体 -->
    <view class="calendar-content">
      <!-- 年月选择器 -->
      <view class="month-selector">
        <view class="arrow" @tap="changeMonth(-1)">←</view>
        <text class="current-month"
          >{{ currentYear }}年{{ currentMonth }}月</text
        >
        <view class="arrow" @tap="changeMonth(1)">→</view>
      </view>

      <!-- 星期表头 -->
      <view class="weekdays">
        <text v-for="day in weekDays" :key="day">{{ day }}</text>
      </view>

      <!-- 日期网格 -->
      <view class="days-grid">
        <view
          class="day-cell"
          v-for="(day, index) in daysArray"
          :key="index"
          :class="{
            'other-month': !day.currentMonth,
            today: day.isToday,
            'has-mood': day.mood,
            selected: day.fullDate === selectedDate,
          }"
          @tap="handleDayClick(day)"
        >
          <text class="date">{{ day.date }}</text>
          <view v-if="day.mood" class="mood-indicator" :class="day.mood"></view>
        </view>
      </view>
    </view>

    <!-- 时间线部分 -->
    <view class="timeline-section">
      <scroll-view
        class="timeline-scroll"
        scroll-x
        enable-flex
        scroll-with-animation
        :scroll-anchoring="true"
        :enhanced="true"
        :show-scrollbar="false"
        :scroll-into-view="lastItemId"
      >
        <view class="mood-timeline">
          <view
            class="timeline-group"
            v-for="(group, groupIndex) in groupedTimelineData"
            :key="groupIndex"
          >
            <text class="group-title">{{ group.yearMonth }}</text>
            <view class="timeline-items">
              <view
                class="timeline-item"
                v-for="(item, index) in group.items"
                :key="index"
              >
                <view class="mood-action" :id="'scrollId' + item.id">
                  <text class="timeline-date">{{ item.day }}日</text>
                  <view
                    class="mood-indicator"
                    v-if="item.mood"
                    :class="item.mood"
                  ></view>
                  <text class="diary-text" @tap="handleDiaryClick(item)">{{
                    item.hasEntry ? "查看" : "记录"
                  }}</text>
                </view>
              </view>
            </view>
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 心情选择弹窗 -->
    <view class="mood-popup" v-if="showMoodPicker">
      <view class="popup-content">
        <view class="popup-header">
          <text class="popup-title">选择今天的心情</text>
          <text class="close-btn" @tap="showMoodPicker = false">×</text>
        </view>
        <view class="mood-list">
          <view
            class="mood-item"
            v-for="mood in moods"
            :key="mood.value"
            @tap="selectMood(mood.value)"
          >
            <image :src="mood.icon" mode="aspectFit"></image>
            <text>{{ mood.label }}</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, nextTick } from "vue";

const currentYear = ref(new Date().getFullYear());
const currentMonth = ref(new Date().getMonth() + 1);
const selectedDate = ref(null);
const showMoodPicker = ref(false);
const lastItemId = ref("");

const weekDays = ["日", "一", "二", "三", "四", "五", "六"];

const moods = [
  { label: "开心", value: "happy" },
  { label: "平静", value: "calm" },
  { label: "疲惫", value: "tired" },
  { label: "焦虑", value: "anxious" },
  { label: "生气", value: "angry" },
].map((mood) => ({
  ...mood,
  icon: `/static/moods/${mood.value}.png`,
}));

const savedMoods = ref({
  "2024-03-21": "happy",
  "2024-03-19": "tired",
  "2024-03-15": "calm",
});

const timelineData = ref([
  { date: "2024年3月15日", hasEntry: false, mood: "calm", id: 1 },
  { date: "2024年3月19日", hasEntry: true, mood: "tired", id: 2 },
  { date: "2024年3月21日", hasEntry: false, mood: "happy", id: 3 },
]);

const daysArray = computed(() => {
  const days = [];
  const firstDay = new Date(currentYear.value, currentMonth.value - 1, 1);
  const lastDay = new Date(currentYear.value, currentMonth.value, 0);
  const firstDayWeekday = firstDay.getDay();

  for (let i = 0; i < firstDayWeekday; i++) {
    const date = new Date(
      currentYear.value,
      currentMonth.value - 1,
      -firstDayWeekday + i + 1
    );
    days.push(createDayObject(date, false));
  }

  for (let i = 1; i <= lastDay.getDate(); i++) {
    const date = new Date(currentYear.value, currentMonth.value - 1, i);
    days.push(createDayObject(date, true));
  }

  const remainingDays = 42 - days.length;
  for (let i = 1; i <= remainingDays; i++) {
    const date = new Date(currentYear.value, currentMonth.value, i);
    days.push(createDayObject(date, false));
  }

  return days;
});

const createDayObject = (date, isCurrentMonth) => {
  const today = new Date();
  const isToday =
    date.getDate() === today.getDate() &&
    date.getMonth() === today.getMonth() &&
    date.getFullYear() === today.getFullYear();

  return {
    date: date.getDate(),
    currentMonth: isCurrentMonth,
    isToday,
    fullDate: formatDate(date),
    mood: savedMoods.value[formatDate(date)],
  };
};

const formatDate = (date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
};

const formatDisplayDate = (date) => {
  if (!date) return "";
  const [year, month, day] = date.split("-");
  return `${year}年${month}月${day}日`;
};

const isToday = (date) => {
  const today = new Date();
  return (
    date.getDate() === today.getDate() &&
    date.getMonth() === today.getMonth() &&
    date.getFullYear() === today.getFullYear()
  );
};

const handleBack = () => uni.navigateBack();

const changeMonth = (delta) => {
  let newMonth = currentMonth.value + delta;
  let newYear = currentYear.value;

  if (newMonth > 12) {
    newMonth = 1;
    newYear++;
  } else if (newMonth < 1) {
    newMonth = 12;
    newYear--;
  }

  currentMonth.value = newMonth;
  currentYear.value = newYear;
};

const handleDayClick = (day) => {
  selectedDate.value = day.fullDate;
  const today = new Date();
  const selectedDateObj = new Date(day.fullDate);

  if (selectedDateObj <= today) {
    if (day.isToday) {
      showMoodPicker.value = true;
    }
  }
};

const selectMood = (mood) => {
  if (!selectedDate.value) return;

  savedMoods.value[selectedDate.value] = mood;
  const formattedDate = formatDisplayDate(selectedDate.value);

  const existingEntryIndex = timelineData.value.findIndex(
    (item) => item.date === formattedDate
  );
  if (existingEntryIndex === -1) {
    const newId = 9;
    const newEntry = {
      date: formattedDate,
      hasEntry: false,
      mood,
      id: newId,
    };
    timelineData.value.push(newEntry);
    nextTick(() => {
      lastItemId.value = `scrollId${newId}`;
    });
  } else {
    timelineData.value[existingEntryIndex].mood = mood;
  }

  showMoodPicker.value = false;
};

const handleDiaryClick = (item) => {
  const route = item.hasEntry ? "edit" : "add";
  uni.navigateTo({
    url: `/pages/diary/${route}?date=${item.date}`,
  });
};

const groupedTimelineData = computed(() => {
  const groups = timelineData.value
    .sort((a, b) => {
      const dateA = new Date(a.date.replace(/年|月|日/g, "/"));
      const dateB = new Date(b.date.replace(/年|月|日/g, "/"));
      return dateA - dateB;
    })
    .reduce((acc, item) => {
      const [year, month] = item.date.match(/(\d{4})年(\d{1,2})月/).slice(1);
      const yearMonth = `${year}年${month}月`;
      const day = item.date.match(/(\d{1,2})日/)[1];

      if (!acc[yearMonth]) {
        acc[yearMonth] = {
          yearMonth,
          items: [],
          timestamp: new Date(`${year}/${month}/1`).getTime(),
        };
      }

      acc[yearMonth].items.push({ ...item, day });
      return acc;
    }, {});

  return Object.values(groups)
    .sort((a, b) => a.timestamp - b.timestamp)
    .map((group) => ({
      yearMonth: group.yearMonth,
      items: group.items.sort((a, b) => parseInt(a.day) - parseInt(b.day)),
    }));
});
</script>

<style lang="scss" scoped>
.calendar-container {
  min-height: 100vh;
  height: 100vh;
  background: #000;
  position: relative;
  display: flex;
  flex-direction: column;
  overflow: hidden;

  .nav-header {
    flex-shrink: 0;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20rpx;
    background: rgba(255, 255, 255, 0.1);

    .back-btn {
      padding: 10rpx;
      .icon {
        color: #fff;
        font-size: 36rpx;
      }
    }

    .title {
      color: #fff;
      font-size: 32rpx;
      font-weight: bold;
    }

    .placeholder {
      width: 60rpx;
    }
  }

  .calendar-content {
    flex: 1;
    overflow-y: auto;
    padding: 20rpx;
    padding-bottom: 240rpx;

    .month-selector {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 40rpx;

      .arrow {
        color: #fff;
        font-size: 32rpx;
        padding: 10rpx 20rpx;
      }

      .current-month {
        color: #fff;
        font-size: 32rpx;
        font-weight: bold;
      }
    }

    .weekdays {
      display: grid;
      grid-template-columns: repeat(7, 1fr);
      text-align: center;
      margin-bottom: 20rpx;

      text {
        color: rgba(255, 255, 255, 0.6);
        font-size: 24rpx;
        padding: 10rpx 0;
      }
    }

    .days-grid {
      display: grid;
      grid-template-columns: repeat(7, 1fr);
      gap: 2rpx;
      background: rgba(255, 255, 255, 0.1);
      border-radius: 12rpx;
      overflow: hidden;

      .day-cell {
        aspect-ratio: 1;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        background: #000;
        position: relative;

        .date {
          color: #fff;
          font-size: 28rpx;
        }

        &.other-month .date {
          color: rgba(255, 255, 255, 0.3);
        }

        &.today {
          background: rgba(102, 126, 234, 0.2);

          .date {
            color: #667eea;
            font-weight: bold;
          }
        }

        &.selected {
          background: rgba(102, 126, 234, 0.3);
        }

        .mood-indicator {
          width: 16rpx;
          height: 16rpx;
          border-radius: 50%;
          margin-top: 8rpx;

          &.happy {
            background: #4caf50;
          }
          &.calm {
            background: #2196f3;
          }
          &.tired {
            background: #ffc107;
          }
          &.anxious {
            background: #ff9800;
          }
          &.angry {
            background: #f44336;
          }
        }
      }
    }
  }

  .timeline-section {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    background: #1a1a1a;
    padding: 20rpx;
    border-top-left-radius: 20rpx;
    border-top-right-radius: 20rpx;
    height: 180rpx;

    .timeline-scroll {
      width: 100%;
      height: 100%;

      .mood-timeline {
        display: flex;
        flex-direction: row;
        padding: 20rpx;
        height: 100%;
        align-items: flex-start;

        .timeline-group {
          flex-shrink: 0;
          margin-right: 40rpx;

          &:last-child {
            margin-right: 0;
          }

          .group-title {
            color: #fff;
            font-size: 28rpx;
            font-weight: bold;
            margin-bottom: 20rpx;
            display: block;
          }

          .timeline-items {
            display: flex;
            flex-direction: row;
            gap: 30rpx;

            .timeline-item {
              width: 200rpx;
              display: flex;
              flex-direction: column;
              align-items: center;

              .mood-action {
                display: flex;
                align-items: center;
                gap: 12rpx;
                .timeline-date {
                  color: rgba(255, 255, 255, 0.8);
                  font-size: 24rpx;
                }
                .mood-indicator {
                  width: 24rpx;
                  height: 24rpx;
                  border-radius: 50%;
                  box-shadow: 0 0 10rpx rgba(0, 0, 0, 0.2);

                  &.happy {
                    background: linear-gradient(135deg, #4caf50, #45a049);
                  }
                  &.calm {
                    background: linear-gradient(135deg, #2196f3, #1e88e5);
                  }
                  &.tired {
                    background: linear-gradient(135deg, #ffc107, #ffb300);
                  }
                  &.anxious {
                    background: linear-gradient(135deg, #ff9800, #fb8c00);
                  }
                  &.angry {
                    background: linear-gradient(135deg, #f44336, #e53935);
                  }
                }

                .diary-text {
                  color: rgba(255, 255, 255, 0.6);
                  font-size: 24rpx;
                }
              }
            }
          }
        }
      }
    }
  }

  .mood-popup {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.8);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1000;

    .popup-content {
      width: 80%;
      background: #1a1a1a;
      border-radius: 20rpx;
      padding: 30rpx;

      .popup-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 30rpx;

        .popup-title {
          color: #fff;
          font-size: 32rpx;
          font-weight: bold;
        }

        .close-btn {
          color: rgba(255, 255, 255, 0.6);
          font-size: 40rpx;
          padding: 10rpx;
        }
      }

      .mood-list {
        display: grid;
        grid-template-columns: repeat(5, 1fr);
        gap: 20rpx;

        .mood-item {
          display: flex;
          flex-direction: column;
          align-items: center;
          gap: 10rpx;

          image {
            width: 80rpx;
            height: 80rpx;
          }

          text {
            color: #fff;
            font-size: 24rpx;
          }
        }
      }
    }
  }
}
</style> 